import { sendSock, createWebSocket, closeSock } from "@/utils/websocketService";
const useWebsocketStore = defineStore(
  'websocket',
  {
    state: () => {
      return {
        /**
         * socket推送过来的全量数据，暴露出去用户对数据变更的监听
        */
        serviceMsg: {}
      }
    },
    actions: {
      /**
      * 连接webSocket init
      */
      init () {
        createWebSocket(this.global_callback);
      },
      /**
       * websocket的回调函数
       * @param jsonMsg 表示收到的消息
      */
      global_callback (jsonMsg) {
        this.serviceMsg = jsonMsg;
      },
      /**
       * webSocket发送消息
       * @param sendData 发送的json数据
      */
      send (sendData) {
        sendSock(JSON.stringify(sendData));
      },

      /**
       * 关闭webSocket
      */
      close ({ isActiveClose = false }) {
        closeSock({ activeClose: isActiveClose });
      },

      /**
       * 关闭后重启socket
      */
      closeAndRestart () {
        this.close({ isActiveClose: true });
        this.init();
      }


    }
  }
);

export default useWebsocketStore;